//
//  ST_PairsVoiceSignPlayControl.swift
//  btvideo
//
//  Created by Jason on 2022/2/25.
//  Copyright © 2022 JarvanZhang. All rights reserved.
//

import UIKit
//import Rswift

class ST_PairsVoiceSignPlayControl: UIControl {
    
    let url:URL
    let duration:Int
    
    init(url:URL,duration:Int){
        
        self.url = url
        self.duration = duration
        
        super.init(frame: .zero)
        
        self.addTarget(self, action: #selector(click_btn), for: .touchUpInside)
        self.cornerRadius = 16
        self.backgroundColor = UIColor(hex: 0, transparency: 0.5)
        
        addSubviews([playBtn,total_seconds_label])
        
        playBtn.snp.makeConstraints { make in
            make.top.left.equalToSuperview().offset(4)
            make.bottom.equalToSuperview().offset(-4)
            make.width.equalTo(playBtn.snp.height)
        }
        
        total_seconds_label.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-17)
            make.centerY.equalToSuperview()
            make.left.equalTo(playBtn.snp.right).offset(9)
        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    fileprivate lazy var playBtn:UIButton = {
        let btn = UIButton.init(type: UIButton.ButtonType.custom)
        btn.isUserInteractionEnabled = false
        btn.setImage(ST_ImageUtils.imageName("pairs_voice_sign_play_icon"), for: .normal)
        btn.setImage(ST_ImageUtils.imageName("pairs_voice_sign_play_icon_sel"), for: .selected)
        return btn
    }()
    
    
    fileprivate lazy var total_seconds_label:UILabel = {
        let l = UILabel()
        l.textColor = .white
        l.text = duration.string + "s"
        l.font = .systemFont(ofSize: 14, weight: .regular)
        return l
    }()
    
    var isPlaying = false{
        didSet{
            playBtn.isSelected = isPlaying
        }
    }
    
    private var player:AVPlayer?
    private var playerItem: AVPlayerItem?
    private var time_observer_token: Any?
    
    private lazy var audio_session: AVAudioSession = {
        let session = AVAudioSession.sharedInstance()
        return session
    }()
}

extension ST_PairsVoiceSignPlayControl{
    
    @objc func click_btn(){
        
        if isPlaying{
            stop()
        }else{
            play()
        }
        
    }
    
    func stop() {
        isPlaying = false
        
        NotificationCenter.default.removeObserver(self)
        
        player = nil
        playerItem = nil
        time_observer_token = nil
        
        NotificationCenter.default.post(name: .personalVideoNeedPlay, object: nil)
    }
    
    func stop_playing(){
        
        isPlaying = false
        
        NotificationCenter.default.removeObserver(self)
        
        player = nil
        playerItem = nil
        time_observer_token = nil
    }
    
    func play(){
        
        do {
            
            try self.audio_session.setCategory(.playback, mode: .default)
            try self.audio_session.setActive(true)
            
            let playerItem = AVPlayerItem(url: url)
            player = AVPlayer(playerItem:playerItem)
            self.playerItem = playerItem
            player?.rate = 1.0;
            player?.play()
            
            NotificationCenter.default.addObserver(self, selector: #selector(player_did_finish_playing(note:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerItem)
            
            isPlaying = true
            
            NotificationCenter.default.post(name: .personalVideoNeedPause, object: nil)
            
        } catch {
            print(error)
        }
        
    }
    
    @objc func player_did_finish_playing(note: NSNotification) {
        
        isPlaying = false
        
        NotificationCenter.default.post(name: .personalVideoNeedPlay, object: nil)
    }
    
}
